//
//  MNDLoginUserModel.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/5.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDLoginUserModel.h"

@implementation MNDLoginUserModel

+ (NSString *)primaryKey {
    return @"user_code";
}

+ (NSArray *)indexedProperties {
    return @[@"user_code"];
}

+ (NSArray *)requiredProperties {
    return @[@"user_code"];
}

//+ (NSArray *)ignoredProperties {
//    return @[@"user_address", @"user_gender", @"use_jx_amount_status",@"open_status"];
//}

+ (BOOL)isUserLogin {
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    
    return user.user_code.length > 0;
}

+ (void)addOrUpdateUser:(MNDLoginUserModel *)user {
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addOrUpdateObject:user];
    }];
}

+ (MNDLoginUserModel *)currentLoginUser {
    RLMResults<MNDLoginUserModel *>  *users = [MNDLoginUserModel allObjects];
    
    MNDLoginUserModel *currentUser = users.firstObject;
    
    return currentUser;
}

+ (MNDLoginUserModel *)userWithUserCode:(NSString *)userCode {
    
    RLMResults<MNDLoginUserModel *> *results = [MNDLoginUserModel objectsWhere: [NSString stringWithFormat:@"user_code = '%@'", userCode]];
    
    MNDLoginUserModel *user = results.firstObject;
    
    return user;
}

+ (void)deleteUserWithUserCode:(NSString *)userCode {
    RLMResults<MNDLoginUserModel *> *results = [MNDLoginUserModel objectsWhere: [NSString stringWithFormat:@"user_code = '%@'", userCode]];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    if (results.count > 0) {
        for (MNDLoginUserModel *user in results) {
            if ([user.user_code isEqualToString:userCode]) {
                [realm transactionWithBlock:^{
                    [realm deleteObject:user];
                }];
            }
        }
    }
}

+ (void)deleteAllUserDatas {
    RLMResults<MNDLoginUserModel *> *results = [MNDLoginUserModel allObjects];
    
    RLMRealm *realm = [RLMRealm defaultRealm];
    
    if (results.count > 0) {
        [realm transactionWithBlock:^{
            [realm deleteObjects:results];
        }];
    }
}

@end
